﻿#include "ssWriteBytes.h"
#include "../ssAssert.h"

namespace StarSeeker
{

ssWriteBytes::ssWriteBytes()
{
}

ssWriteBytes::ssWriteBytes(u32 size, MEM_MGR_TYPE type)
{
	Set(size, type);
}

ssWriteBytes::ssWriteBytes(char* buffer, u32 size)
{
	Set(buffer, size);
}

ssWriteBytes::ssWriteBytes(const ssWriteBytes& wb)
{
	CopyFrom(wb);
}

ssWriteBytes::~ssWriteBytes()
{
	Clear();
}

void ssWriteBytes::operator=(const ssWriteBytes& wb)
{
	CopyFrom(wb);
}

bool ssWriteBytes::Set(u32 size, MEM_MGR_TYPE type)
{
	if(!m_buffer.Buf())
	{
		return m_buffer.Init(size, type);
	}
	return false;
}

bool ssWriteBytes::Set(char* buffer, u32 size)
{
	if(buffer && !m_buffer.Buf())
	{
		return m_buffer.Init(buffer, size);
	}
	return false;
}

bool ssWriteBytes::WriteString(const char* psz, ulint len)
{
	return WriteStruct(psz, len);
}

bool ssWriteBytes::WriteString(std::string& str)
{
	return WriteStruct(str.c_str(), str.size());
}

bool ssWriteBytes::WriteStruct(const void* pbuf, ulint len)
{
	bool ret = false;
	u32 len2 = (u32)len;
	if (m_buffer.MemType()<MEM_MGR_NEW && len+cg_u32_size+m_buffer.Size() > m_buffer.MaxSize())
	{
		SS_ASSERT_DEBUG(false);
		return false;
	}
	ret = m_buffer.Write(&len2, cg_u32_size);
	if (len>0 && ret)
	{
		ret = m_buffer.Write(pbuf, len);
	}
	return ret;
}

bool ssWriteBytes::Resize(ulint size)
{
	return m_buffer.Resize(size, false);
}

void ssWriteBytes::Clear()
{
	m_buffer.Clear();
}

bool ssWriteBytes::WriteBuffer(const void* p, ulint size)
{
	return m_buffer.Write(p, size);
}

void ssWriteBytes::CopyFrom(const ssWriteBytes& wb)
{
	m_buffer = wb.m_buffer;
}

}
